package com.ciwong.epaper.modules.scan.util;

import com.google.zxing.Result;
import com.google.zxing.ResultPoint;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.scan.bean.AnswerCard;
import com.ciwong.epaper.modules.scan.bean.HomeWorkCommitInfo;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.zxing.camera.SaveBitmap;

import android.graphics.Bitmap;
import android.text.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * 扫码辅助类封装 可提交作业 Created by res-zwyan on 2015/8/3.
 */
public class ScanHandler
{
    private final String tag = ScanHandler.class.getSimpleName();

    /**
     * 当前已提交作业份数
     */
    private int mWorkCount = 0;

    // /**
    // * 试卷编码
    // */
    // private long mCodeId;
    //
    // private long mClassId;
    //
    // private String mClassName;

    private HomeWorkData mHomeWorkData = new HomeWorkData();

    /**
     * 答题卡
     */
    private final ArrayList<AnswerCard> mAnswercardList = new ArrayList<AnswerCard>();

    private static ScanHandler me;

    /**
     * 拍完答题卡所存的路径
     */
    private String answerCardSavePath = "";

    private String uuid;

    private ScanHandler()
    {
    }

    private ArrayList<AnswerCard> cloneAnswerCardData()
    {

        int size = mAnswercardList.size();
        ArrayList<AnswerCard> answercardList = new ArrayList<AnswerCard>();
        for (int i = 0; i < size; i++)
        {
            answercardList.add(mAnswercardList.get(i).clone());
        }
        return answercardList;
    }

    // /**
    // * 设置答题卡编码
    // *
    // * @param mCodeId
    // * 编码
    // */
    // public void setCodeId(long mCodeId)
    // {
    // this.mHomeWorkData.mCodeId = mCodeId;
    // }
    //
    // public long getCodeId()
    // {
    // return mHomeWorkData.mCodeId;
    // }
    //
    // public long getClassId()
    // {
    // return mHomeWorkData.mClassId;
    // }
    //
    // public void setClassId(long mClassId)
    // {
    // this.mHomeWorkData. = mClassId;
    // }
    //
    // /**
    // * 清除答題卡id
    // */
    // public void clearCodeId()
    // {
    // this.mHomeWorkData.mCodeId = 0;
    // }
    //
    // public String getClassName()
    // {
    // return mClassName;
    // }
    //
    // public void setClassName(String className)
    // {
    // this.mClassName = className;
    // }

    /**
     * 获取
     * {@link com.ciwong.epaper.modules.scan.util.ScanHandler.HomeWorkData}
     * 
     * @return
     */
    public HomeWorkData getHomeWorkData()
    {
        return mHomeWorkData;
    }

    public void test(float[][] ct, final long userId, BaseCallBack callBack)
    {
        String localpath = getAnswerCardSavePath().replace(ESystem.MEDIA, "")
                + getLastAnswerCard();
    }

    public static ScanHandler me()
    {
        if (me == null)
        {
            synchronized (ScanHandler.class)
            {
                if (me == null)
                {
                    me = new ScanHandler();
                }
            }
        }
        return me;
    }

    /**
     * 是否有答题卡
     *
     * @return true 有 false 没有
     */
    public boolean hasAnswerCard()
    {
        return mAnswercardList.size() > 0;
    }

    /**
     * 提交作业
     */
    public void commitHomework(HomeWorkCommitInfo commitInfo,
            final BaseCallBack baseCallBack)
    {
        ArrayList<AnswerCard> answerCardArrayList = cloneAnswerCardData();
        EpaperDao.getInstance().packSubmitAnswer(commitInfo.getUserId(),
                uuid, commitInfo.getAnswer(), answerCardArrayList,
                commitInfo.getmDownLoadInfo(), commitInfo.getmModule(),
                commitInfo.getPosition(), new BaseCallBack()
                {
                    @Override
                    public void failed(Object data)
                    {
                        CWLog.d(tag, "da bao shi bai");
                        baseCallBack.failed(data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        CWLog.d(tag, "da bao shi bai");
                        baseCallBack.failed(errorCode, data);
                    }

                    @Override
                    public void success()
                    {
                        CWLog.d(tag, "da bao cheng gong");
                        mAnswercardList.clear();
                        baseCallBack.success();
                    }
                });

    }

    /**
     * 将要准备做新作业
     */
    public void preparedoNewHomeWork()
    {
        mAnswercardList.clear();
        answerCardSavePath = "";
        uuid = "";
    }

    /**
     * 本次批处理作业做完
     */
    public void doBatchHomeWorkEnd()
    {
        mHomeWorkData.mCodeId = 0;
        // clearCodeId();
        mWorkCount = 0;
    }

    /**
     * 增加一份
     */
    public synchronized void addWorkCount()
    {
        mWorkCount++;
    }

    /**
     * 获取当前作业份数
     * 
     * @return
     */
    public synchronized int getWorkCount()
    {
        return mWorkCount;
    }

    /**
     * 保存答题卡图片
     */
    public boolean saveAnswerCard(Bitmap bitmap, Result result)
    {
        boolean saveIsSuc = false;
        if (bitmap == null || bitmap.isRecycled())
        {
            return saveIsSuc;
        }
        if (TextUtils.isEmpty(answerCardSavePath) || TextUtils.isEmpty(uuid))
        {
            uuid = UUID.randomUUID().toString();
            answerCardSavePath = ESystem.getAnswersMediaPath(uuid);
        }
        String answerCardName = UUID.randomUUID().toString()
                + EConstants.IMG_DEFAULT_SUFFIX;
        saveIsSuc = saveBitmap(bitmap, answerCardSavePath, answerCardName);
        AnswerCard answerCard = new AnswerCard();
        answerCard.setContent(ESystem.MEDIA + File.separator + answerCardName);
        answerCard.setAnswerCardName(answerCardName);
        // ZxingUtil.zxingResultToZArray(result)
        float[][] loacation = new float[][]{{0, 0}, {0, 0}, {0, 0}, {0, 0}};
        answerCard.setLocation(loacation);
        mAnswercardList.add(answerCard);
        return saveIsSuc;
    }

    private boolean saveBitmap(Bitmap bitmap, String path,
            String answerCardName)
    {
        File mkDir = new File(path, answerCardName);
        return !TextUtils.isEmpty(
                SaveBitmap.saveBitmap(bitmap, mkDir.getAbsolutePath()));
    }

    /**
     * 添加答题卡
     * 
     * @param ac
     *            答题卡
     */
    public void addAnswerCard(AnswerCard ac)
    {
        mAnswercardList.add(ac);
    }

    /**
     * 删除答题卡
     * 
     * @param ac
     *            AnswerCard 答题卡
     */
    public void deleteAnswerCard(AnswerCard ac)
    {
        mAnswercardList.remove(ac);
    }

    public int getAnswercardSize()
    {
        return mAnswercardList.size();
    }

    public List<AnswerCard> getAnswerCard()
    {
        List<AnswerCard> answerCards = new ArrayList<>();
        Iterator<AnswerCard> iterator = mAnswercardList.iterator();
        while (iterator.hasNext())
        {
            answerCards.add(iterator.next().clone());
        }
        return answerCards;
    }

    /**
     * 删除答题卡
     * 
     * @param index
     */
    public void deleteAnswerCard(int index)
    {
        try
        {
            mAnswercardList.remove(index);
        }
        catch (IndexOutOfBoundsException e)
        {
            e.printStackTrace();
        }
    }

    public String getAnswerCardSavePath()
    {
        return answerCardSavePath;
    }

    public AnswerCard getLastAnswerCard()
    {
        AnswerCard answercard = null;
        if (mAnswercardList.size() > 0)
        {
            answercard = mAnswercardList.get(mAnswercardList.size() - 1);
        }
        return answercard;
    }

    public static class ZxingUtil
    {
        /**
         * ResultPoint 转坐标数组
         *
         * @param point
         *            ResultPoint
         * @return float[]
         */
        public static float[] pointToZArray(ResultPoint point)
        {
            float[] result = new float[2];
            if (point != null)
            {
                result[0] = point.getX();
                result[1] = point.getY();
            }
            return result;
        }

        public static float[][] zxingResultToZArray(
                com.google.zxing.Result zxingResult)
        {
            ResultPoint[] resultPoints;
            float[][] result = null;
            if (zxingResult == null)
            {
                return result = new float[1][1];
            }
            resultPoints = zxingResult.getResultPoints();

            if (resultPoints != null)
            {
                result = new float[resultPoints.length][];
                for (int i = 0; i < resultPoints.length; i++)
                {
                    result[i] = pointToZArray(resultPoints[i]);
                }
            }
            return result;
        }
    }

    /**
     * 提交作业时需要保存的数据
     */
    public static class HomeWorkData
    {
        /**
         * 试卷编码id
         */
        private long mCodeId;

        private String textPaperName = "";

        /**
         * 选中班级
         */
        private Clazz mClazz;

        private String mDoworkId = "";

        public long getCodeId()
        {
            return mCodeId;
        }

        public void setCodeId(long mCodeId)
        {
            this.mCodeId = mCodeId;
        }

        public String getTextPaperName()
        {
            return textPaperName;
        }

        public void setTextPaperName(String textPaperName)
        {
            this.textPaperName = textPaperName;
        }

        public Clazz getClazz()
        {
            return mClazz;
        }

        public void setClazz(Clazz clazz)
        {
            mClazz = clazz;
        }

        public void clearCodeId()
        {
            mCodeId = 0;
        }

        public String getDoworkId()
        {
            return mDoworkId;
        }

        public void setDoworkId(String mDoworkId)
        {
            this.mDoworkId = mDoworkId;
        }

        public void setAnswerData(Answer answer)
        {
            if (answer != null)
            {
                Clazz clazz = new Clazz();
                clazz.setClassId(Long.valueOf(answer.getClassId()));
                this.setClazz(clazz);
                this.setCodeId(answer.getCodeId());
                this.setDoworkId(answer.getDoWorkId());
                this.textPaperName = answer.getResourceName();
            }
        }

        public void clear()
        {
            mCodeId = 0;
            mClazz = null;
            textPaperName = "";
            mDoworkId = "";
        }
    }
}
